#include "ACUAS/ACUAS.h"
#include "ACUAS/ACUASlcd.h"

//Read data
//Convert data
//Output data to LCD

double zero_x, zero_y, ninety_x, ninety_y, xdeg, ydeg;


void calibration()
{
	LCD_XY(1,1)
	LCD_TEXT("set sensor for 0")
	LCD_XY(1,2)
	LCD_TEXT("and press joystick up")
	WAIT_FOR_JOYSTICK_UP{
		CLEAR_LCD
	}
	ADC_CHANNEL(1)	//ADC channel 1 used for x axis	conversion
	ADCONVERT_MV(zero_x)
	ADC_CHANNEL(2)	//ADC channel 1 used for y axis	conversion
	ADCONVERT_MV(zero_y)
	LCD_XY(1,1)
	LCD_TEXT("calibration for 0")
	LCD_XY(1,2)
	LCD_TEXT("done")
	WAIT_SEC(1)
	CLEAR_LCD
	LCD_XY(1,1)
	LCD_TEXT("set sensor for 90")
	LCD_XY(1,2)
	LCD_TEXT("and press joystick up")
	WAIT_FOR_JOYSTICK_UP{
		CLEAR_LCD
	}
	ADC_CHANNEL(1)	//ADC channel 1 used for x axis	conversion
	ADCONVERT_MV(ninety_x)
	ADC_CHANNEL(2)	//ADC channel 1 used for y axis	conversion
	ADCONVERT_MV(ninety_y)
	LCD_XY(1,1)
	LCD_TEXT("calibration for 90")
	LCD_XY(1,2)
	LCD_TEXT("done")
	WAIT_SEC(2)
	CLEAR_LCD
}


PROGRAM_INIT
//calibrate sensor if necessary 
//interpolate the rest 
	ACTIVATE_LCD
	ACTIVATE_ADC

	double x,y;
	char flag;

	LCD_XY(1,1)
	LCD_TEXT("to calibrate press j_up")
	LCD_XY(1,2)
	LCD_TEXT("to measure press j_down")

	while (flag & 0b01010000) //wait till the j_up or j_down is pressed 
 	}			  // and assign the choice to the flag			
		flag = PINA;
	}
	CLEAR_LCD

	if ( !(flag | 0b10111111) ) //check if j_up is pressed(bit 7 is 0)
	{
		calibration();
	}

PROGRAM_START
		
		ADC_CHANNEL(1)	//ADC channel 1 used for x axis	conversion
		ADCONVERT_MV(x)

		ADC_CHANNEL(2)	//ADC channel 2 used for y axis conversion
		ADCONVERT_MV(y)

		
		xdeg = ( (90.) / (ninety_x - zero_x) ) * (x - zero_x);
		ydeg = ( (90.) / (ninety_y - zero_y) ) * (x - zero_y);
					
		LCD_XY(1,1)
		LCD_NUMBER(xdeg)

		LCD_XY(1,2)
		LCD_NUMBER(ydeg) 
	
PROGRAM_END
